﻿#include "knowledgebase.h"
#include "ui_knowledgebase.h"
#include "plugins/KnowledgeBase/knowledgebaseconfigwidget.h"
#include "constants.h"
#include "kbcreatefolderwizard.h"
#include "globle.h"

KnowledgeBase::KnowledgeBase(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::KnowledgeBase)
{
    ui->setupUi(this);
    //this->ui->treeViewCategory->setSizeIncrement();
    getTreeFromLocalDir();
}

KnowledgeBase::~KnowledgeBase()
{
    delete ui;
}
void KnowledgeBase::getTreeFromLocalDir()
{
    qDebug("read the ini");

    //QSettings settings(QSettings::IniFormat,QSettings::UserScope,INI_ORGANIZATION,"app");
    QString qLuoshuRoot = qApp->getSettings()->value(INI_ROOT_DIR,QVariant("")).toString();
    if (qLuoshuRoot.isEmpty())
    {
        // 显示配置窗口
        Qt::WindowFlags flags = 0;
        KnowledgebaseConfigWidget* pDlg = new KnowledgebaseConfigWidget();
        flags = pDlg->windowFlags();
        flags |= Qt::WindowCloseButtonHint;
        pDlg->setWindowFlags(flags);
        pDlg->exec();
        qLuoshuRoot = pDlg->getRootDir();

        // 写配置文件
        qApp->getSettings()->setValue(INI_ROOT_DIR,QVariant(qLuoshuRoot));
        //.value(INI_ROOT_DIR,QVariant("")).toString();

        // 建立初始化模板 用户第一次运行程序的时候，帮助用户建立知识管理文件夹结构
        KbCreateFolderWizard* fw = new KbCreateFolderWizard(this);
        fw->exec();

        pDlg->deleteLater();
        fw->deleteLater();
    }

	// 检查配置文件的目录情况
    {

        QDir f(qLuoshuRoot);

        if (!f.exists())
        {
            // 提示是否创建文件夹
            f.mkdir(qLuoshuRoot);
        }

        // 目录为空的时候，重新运行向导
		QStringList dirs = f.entryList(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
        if (0 == dirs.size())
        {
            // 建立初始化模板 用户第一次运行程序的时候，帮助用户建立知识管理文件夹结构
            KbCreateFolderWizard* fw = new KbCreateFolderWizard(0);
            fw->exec();
            fw->deleteLater();
        }
    }

    //this->ui->treeViewCategory->setGeometry(this->ui->pageCategory->geometry());
    model = new QFileSystemModel();
    model->setRootPath(qLuoshuRoot);
    this->ui->treeViewCategory->setModel(model);
    this->ui->treeViewCategory->header()->setStretchLastSection(true);
    this->ui->treeViewCategory->header()->setSortIndicator(0, Qt::AscendingOrder);
    this->ui->treeViewCategory->header()->setSortIndicatorShown(true);
    this->ui->treeViewCategory->header()->setClickable(true);

    QModelIndex indexRoot = model->index(qLuoshuRoot);
    this->ui->treeViewCategory->expand(indexRoot);
    this->ui->treeViewCategory->setRootIndex(indexRoot);

}

void KnowledgeBase::on_treeViewCategory_clicked(QModelIndex index)
{
    QString str = model->filePath(index);
    emit userSelectedPath(str);
}


